import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import { loadEnv } from 'vite'
import path from "path"

// 引入三个环境的配置文件
import ViteBaseConfig from './viteconfig/vite.base.config'
import ViteProdConfig from './viteconfig/vite.prod.config'
import ViteDevConfig from './viteconfig/vite.dev.config'

// 合并环境配置
const envResolver = {
  'build': () => {
    console.log("加载生产环境 : ")
    // 解构的语法
    return ({ ...ViteBaseConfig, ...ViteProdConfig })
  },
  "serve": () => {
    console.log("加载开发环境 : ")
    // 另一种写法
    // return Object.assign({}, ViteBaseConfig, ViteDevConfig)
    return ({ ...ViteBaseConfig, ...ViteDevConfig})
  }
}


export default defineConfig(({ command, mode }) => {
  console.log("vite start : command : ", command)
  console.log("vite start : mode : ", mode)
  console.log("process.cwd() : ", process.cwd())
  console.log("__dirname: ", __dirname)
  console.log("envdir ： ", path.resolve(process.cwd(),'./environmentconfig'))
  // 加载不同环境下参数
  const envParams = loadEnv(mode, path.resolve(process.cwd(),'./environmentconfig'))
  console.log("env.VITE_TARGET_URL:", envParams);
  console.log("env.VITE_TARGET_URL:", envParams.VITE_TARGET_URL);

  console.log("开始合并环境")
  const mergeConfig =  envResolver[command]()
  // console.log("合并配置：", mergeConfig);
  mergeConfig.server = {
    proxy: {
      '/api': {   // 获取路径中包含了/api的请求
          //target: 'http://192.168.1.51:8999',        // 服务端地址
          target: envParams.VITE_TARGET_URL,
          changeOrigin: true, // 修改源
          rewrite:(path) => path.replace(/^\/api/, '')   // api 替换为 ''

      }
  }
  }

  return mergeConfig
})
